<template>
  <div style="width: 100%" class="property-notice-section">
    <h2 class="section-title">通知管理</h2>
    <div class="search-bar">
      <div class="left-search-group">
        <el-input v-model="currentPage" placeholder="请输入当前页面" style="width: 150px;"></el-input>
        <el-input v-model="pageSize" placeholder="请输入每页大小" style="width: 150px;"></el-input>
        <el-input v-model="title" placeholder="请输入通知标题" style="width: 150px;"></el-input>
        <el-button @click="getPropertyNotice" class="search-button">查询</el-button>
      </div>
      <div class="right-search-group">
        <el-input v-model="noticeId" placeholder="请输入通知id" style="width: 150px;"></el-input>
        <el-button @click="getNoticeById" class="search-button">根据id查询详情</el-button>
        <el-button @click="publishDialogVisible = true" class="publish-button">发布通知</el-button>
        <el-button @click="publishToPayNotice" class="publish-button">发布催缴费通知</el-button>
      </div>
    </div>
    <div v-if="isLoading" class="loading-container">加载中···</div>
    <el-table v-else :data="propertyNotices" stripe style="width: 100%" class="notice-table">
      <el-table-column prop="id" label="通知ID" width="100"></el-table-column>
      <el-table-column prop="title" label="通知标题"></el-table-column>
      <el-table-column prop="publishDate" label="发布时间" width="180"></el-table-column>
      <el-table-column prop="updateDate" label="更新时间" width="180"></el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column prop="propertyStaffId" label="发布人ID" width="120"></el-table-column>
      <el-table-column label="附件" width="150">
        <template #default="{ row }">
          <el-button v-if="row.attachment" type="text" @click="downloadFile(row.attachment)">下载附件</el-button>
          <span v-else>无</span>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination-component"
    >
    </el-pagination>

    <!-- 发布通知对话框 -->
    <el-dialog v-model="publishDialogVisible" title="发布通知">
      <el-form :model="newNoticeForm">
        <el-form-item label="通知标题" prop="title">
          <el-input v-model="newNoticeForm.title"></el-input>
        </el-form-item>
        <el-form-item label="通知内容" prop="content">
          <el-input type="textarea" v-model="newNoticeForm.content"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="newNoticeForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="附件">
          <input type="file" ref="fileInput" @change="handleFileChange" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="publishDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="publishNotice">发布</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogVisible" title="通知详情">
      <div v-if="noticeDetail" class="notice-detail">
        <p><strong>通知 ID:</strong> {{ noticeDetail.id }}</p>
        <p><strong>通知标题:</strong> {{ noticeDetail.title }}</p>
        <p><strong>内容:</strong> {{ noticeDetail.content }}</p>
        <p><strong>发布时间:</strong> {{ noticeDetail.publishDate }}</p>
        <p><strong>更新时间:</strong> {{ noticeDetail.updateDate }}</p>
        <p><strong>备注:</strong> {{ noticeDetail.remark }}</p>
        <p><strong>发布人 ID:</strong> {{ noticeDetail.propertyStaffId }}</p>
        <p v-if="noticeDetail.attachment"><strong>附件:</strong> <el-button type="text" @click="downloadFile(noticeDetail.attachment)">下载附件</el-button></p>
        <p v-else><strong>附件:</strong> 无附件</p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import axios from 'axios';
import {ElMessage} from 'element-plus';

// 获取 token
const token = localStorage.getItem('token');
const headers = {
  Authorization: token
};

// 分页查询通知相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const title = ref('');
const propertyNotices = ref([]);
const isLoading = ref(false);

// 根据通知 ID 查询通知详情相关
const noticeId = ref('');
const noticeDetail = ref(null);
const dialogVisible = ref(false);

// 发布通知相关
const publishDialogVisible = ref(false);
const newNoticeForm = ref({
  title: '',
  content: '',
  remark: '',
  attachment: null
});
const fileInput = ref(null);

// 文件选择事件处理函数
const handleFileChange = (event) => {
  newNoticeForm.value.attachment = event.target.files[0];
};

onMounted(() => {
  getPropertyNotice();
});

// 分页查询通知
const getPropertyNotice = async () => {
  isLoading.value = true;
  // 在查询时，如果输入框为空，恢复默认值
  if (currentPage.value === '') {
    currentPage.value = 1;
  }
  if (pageSize.value === '') {
    pageSize.value = 10;
  }
  try {
    const response = await axios.get('/api/notice/property', {
      headers,
      params: {
        current: parseInt(currentPage.value),
        size: parseInt(pageSize.value),
        title: title.value
      }
    });
    if (response.data.code === 200) {
      propertyNotices.value = response.data.data.records;
      total.value = response.data.data.total;
    } else {
      ElMessage.error('查询通知失败: ' + response.data.message);
    }
  } catch (error) {
    ElMessage.error('查询通知失败: ' + error.message);
  } finally {
    isLoading.value = false;
  }
};

// 根据通知ID查询通知详情
const getNoticeById = async () => {
  isLoading.value = true;
  const id = noticeId.value;
  if (!id) {
    ElMessage.warning('请输入通知ID');
    isLoading.value = false;
    return;
  }
  try {
    const response = await axios.get(`/api/notice/all/${id}`, { headers });
    if (response.data.code === 200) {
      noticeDetail.value = response.data.data[0];
      dialogVisible.value = true;
    } else {
      ElMessage.error('查询通知详情失败: ' + response.data.message);
    }
  } catch (error) {
    ElMessage.error('查询通知详情失败: ' + error.message);
  } finally {
    isLoading.value = false;
  }
};

// 处理分页大小改变
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  getPropertyNotice();
};

// 处理当前页码改变
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getPropertyNotice();
};

// 发布通知
const publishNotice = async () => {
  isLoading.value = true;
  const formData = new FormData();
  formData.append('title', newNoticeForm.value.title);
  formData.append('content', newNoticeForm.value.content);
  if (newNoticeForm.value.remark) {
    formData.append('remark', newNoticeForm.value.remark);
  }
  if (newNoticeForm.value.attachment) {
    formData.append('attachment', newNoticeForm.value.attachment);
  }

  try {
    const response = await axios.post('/api/notice/property/publish', formData, {
      headers: {
        ...headers,
        'Content-Type': 'multipart/form-data'
      }
    });
    if (response.data.code === 200) {
      ElMessage.success('发布通知成功');
      publishDialogVisible.value = false;
      newNoticeForm.value = {
        title: '',
        content: '',
        remark: '',
        attachment: null
      };
      fileInput.value.value = '';
      getPropertyNotice();
    } else {
      ElMessage.error('发布通知失败: ' + response.data.message);
    }
  } catch (error) {
    ElMessage.error('发布通知失败: ' + error.message);
  } finally {
    isLoading.value = false;
  }
};

// 发布催缴费通知
const publishToPayNotice = async () => {
  isLoading.value = true;
  try {
    const response = await axios.post('/api/notice/property/publish/toPay', null, { headers });
    if (response.data.code === 200) {
      ElMessage.success('发布催缴费通知成功');
      getPropertyNotice();
    } else {
      ElMessage.error('发布催缴费通知失败: ' + response.data.message);
    }
  } catch (error) {
    ElMessage.error('发布催缴费通知失败: ' + error.message);
  } finally {
    isLoading.value = false;
  }
};

// 下载附件方法
const downloadFile = async (path) => {
  try {
    const response = await axios.get('/api/file', {
      params: {
        path: path
      },
      headers: {
        Authorization: token
      },
      responseType: 'blob'
    });
    const blob = new Blob([response.data], { type: response.headers['content-type'] });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    const contentDisposition = response.headers['content-disposition'];
    a.download = contentDisposition ? contentDisposition.split('filename*=UTF-8\'\'')[1] : 'downloaded_file';
    a.click();
    window.URL.revokeObjectURL(url);
    ElMessage.success('文件下载成功');
  } catch (error) {
    ElMessage.error('文件下载失败：' + error.message);
  }
};

</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}
.left-search-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.right-search-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.notice-table {
  margin-bottom: 10px;
}

.pagination-component {
  margin-top: 10px;
  text-align: center;
}

.notice-detail {
  padding: 10px;
}

.publish-button {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 3px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.publish-button:hover {
  background-color: #66b1ff;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  font-size: 16px;
  color: #666;
}
</style>